<?php
/**2012-9-25 by yzw

 * @Description:创建文件名
 * @param:$filename:文件名，一般为文本文件(abc.txt/abc)
		  $suffix:文件后缀名(txt/php/js)
 * @remark:返回完整文件名
 */
function mkfileName($filename,$suffix="txt")
{
	$basename = basename($filename);
	if($basename === $filename)
	{
		$cut = explode('.',$basename);
		$fix = end($cut);
		if(count($cut)>1)
		{
			if(in_array($fix,array('txt','php','js')))
			{
				$result = $basename;
			}else{
				$result = $basename.'.'.$suffix;
			}
		}else{
			$result = $basename.'.'.$suffix; 
		}
	}else{
		exit('文件名格式不正确...');
	}
	return $result;
}

/**
 * @Description:writeFile 写入文件函数
 * @param:$data:写入内容，serialize数据 或者数组
		  $filename:文件名，一般为文本文件(abc.txt)
		  $dir:文件目录
		  $type:写入方式log/update形式
 * @remark:返回true/false
 */
function writeFile($filename,$data,$type="other",$dir="txtdb")
{
	if(is_array($data))
	{
		$string = serialize($data);
	}else{
		$string = $data;
	}
	$filename = mkfileName($filename);
	$file = realpath(dirname(dirname(__FILE__))).'\\'.$dir;
	if(!is_dir($file))
	{
		mkdir($file,0777,true);
	}
	$txt = $file.'\\'.$filename;
	switch($type)
	{
		case 'log':
			if(!$opfile = fopen($txt,'a+'))
			{
				return false;
			}
			$sever = php_uname('s');//判断服务器信息
			switch($sever)
			{
				case 'Linux':
					$result = fwrite($opfile,$string."\n");
					break;
				default:
					$result = fwrite($opfile,$string."\r\n");
					break;
			}
			break;
		default:
			if(!$opfile = fopen($txt,'w'))
			{
				return false;
			}
			$result = fwrite($opfile,$string);
			break;
	}
	fclose($opfile);
	return $result===false ? false:true;
}

/**
 * @Description:writeFile 读取文件函数
 * @param:$filename:文件名，一般为文本文件(abc.txt/abc)
		  $type:写入方式log/update形式
		  $dir:文件目录		  
 * @remark:返回数组
 */
function getFile($filename,$type="other",$dir="txtdb")
{
	$txt = realpath(dirname(dirname(__FILE__))).'\\'.$dir.'\\'.mkfileName($filename);
	
	if(file_exists($txt))
	{
		$content = file_get_contents($txt);
		switch($type)
		{
			case 'log':
				$sever = php_uname('s');//判断服务器信息
				switch($sever)
				{
					case 'Linux':
						$result = array_filter(explode("\n", $content));
						break;
					default:
						$result = array_filter(explode("\r\n", $content));
						break;
				}
				foreach($result as &$val)
				{
					$val = unserialize($val);
				}
				break;
			default:
				$result = unserialize($content);
				break;
		}
	}else{
		$result === false;
	}
	return $result;
}

?>